﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Simple.Services.System.Jobs
{
    public class TimerTaskService
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private static int _interval;
        private static bool _isRunning = false;
        private static Func<Task> _taskAction;
        private Task _timer;
        private static readonly object _lock = new object();

        public TimerTaskService(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;
        }

        public void Initialize(int interval, Func<Task> action)
        {
            _interval = interval;
            _taskAction = action;
        }

        public void Start()
        {
            if (_taskAction == null)
            {
                throw new InvalidOperationException("TimerTaskService is not initialized.");
            }

            lock (_lock)
            {
                if (_isRunning)
                {
                    return;
                }

                _isRunning = true;

                if (_timer == null || _timer.IsCompleted)
                {
                    _timer = Task.Run(async () => await RunTask());
                }
            }
        }

        public void Stop()
        {
            lock (_lock)
            {
                _isRunning = false;
            }
            _timer?.Wait();
            _timer?.Dispose();
            _timer = null;
        }
        public bool IsRunning()
        {
            return _isRunning;
        }
        private async Task RunTask()
        {
            while (_isRunning)
            {
                await _taskAction();
                await Task.Delay(_interval);
            }
        }

        public async Task<DangerMsg> GetDangerAsync(CancellationToken cancellationToken)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<SimpleDbContext>();
                var validDangerTypes = new List<string> { "一般隐患", "较大隐患", "重大隐患" };
                var data = DateTime.Now.AddSeconds(-20);
                var danger = await dbContext.Set<QHSESysDanger>()
                    .AsNoTracking()
                    .Where(u =>   validDangerTypes.Contains(u.DangerType) && u.EnterTime >= data)
                    .Select(u => new DangerMsg()
                    {
                        Time = u.EnterTime,
                        Id = u.QhseXyDangerId,
                        Type = u.DangerType,
                        OrgId = u.SecondOrganizationId
                    })
                    .FirstOrDefaultAsync(cancellationToken);
                return danger;
            }
        }

        public async Task<DangerMsg> GetViolationAsync(CancellationToken cancellationToken)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<SimpleDbContext>();

                var data = DateTime.Now.AddSeconds(-15);
                var violation = await dbContext.Set<QHSESysXyViolation>()
                    .AsNoTracking()
                    .Where(u => u.EnterTime >= data && u.ViolationType != "轻微行为违章")
                    .Select(u => new DangerMsg()
                    {
                        Time = u.EnterTime,
                        Id = u.QhseXyViolationId,
                        Type = u.ViolationType,
                        OrgId = u.SecondOrganizationId
                    })
                    .FirstOrDefaultAsync(cancellationToken);
                return violation;
            }
        }
    }





}
